#include<stdlib.h>
#include<stdio.h>
#include<string.h>

/***********************************
 * usage: 
 * export PI=3.14
 * ./a.out PI 3.1415926
 * or:
 * PI=3.14 ./a.out PI 3.1415926
***********************************/

int main(int argc, char* argv[])
{
	char* var;
	char* value;

	if (argc == 1 || argc > 3)
	{
		printf("usage: %s var [value]\n", argv[0]);
		exit(1);
	}

	var = argv[1];
	value = getenv(var);
	if (NULL != value)
	{
		printf("Variable %s has value %s\n", var, value);
	}
	else
	{
		printf("Variable %s has no value\n", var);
	}

	if (3 == argc)
	{
		int res = 0;
		char* string;
		value = argv[2];

		string = malloc(strlen(var) + strlen(value) + 2);
		strcpy(string, var);
		strcat(string, "=");
		strcat(string, value);

		res = putenv(string);
		if (0 != res)
		{
			printf("putenv failed\n");
			free(string);
			exit(1);
		}
		//free(string);		//caution: must not free here!!!
	}

	value = getenv(var);
	if (NULL != value)
	{
		printf("Variable %s has value %s\n", var, value);
	}
	else
	{
		printf("Variable %s has no value\n", var);
	}

	return 0;
}


